package com.misty.common.Util;

import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @author Cthultu
 */
@Slf4j
public class SecurityUtil {

    public static Object getPrincipal() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(ObjectUtil.isEmpty(principal)){
            return null;
        }
        return principal;
    }

    public static String getUserName() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(ObjectUtil.isEmpty(authentication)){
            return null;
        }
        return authentication.getName();
    }


    public static Authentication getAuthentication() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(ObjectUtil.isEmpty(authentication)){
            return null;
        }
        log.info("============authentication================:  ");
        log.info(String.valueOf(authentication instanceof AnonymousAuthenticationToken));
        log.info(authentication.toString());
        return authentication;
    }

    public static boolean judgeLogin() {
        //判断登录
        Authentication authentication = getAuthentication();
        if((authentication instanceof AnonymousAuthenticationToken) || ObjectUtil.isNull(authentication)){
            return false;
        }
        return true;
    }

}
